package com.sun.showcase.conf.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.sun.showcase.biz.basic.service.ResourceInfoService;
import com.sun.showcase.biz.basic.service.UserInfoService;
import com.sun.showcase.client.domain.basic.ResourceInfo;
import com.sun.showcase.client.domain.basic.UserInfo;
import com.sun.showcase.utils.ResourceTypeEnum;

public class UserDetailsServiceImpl implements UserDetailsService{

	@Resource
	private UserInfoService userInfoService;
	
	@Resource
	private ResourceInfoService resourceInfoService;
	
	public UserDetails loadUserByUsername(String userName)throws UsernameNotFoundException {
		
		UserInfo t = userInfoService.getByName(userName);
		
		if(null == t)
			throw new UsernameNotFoundException("用户 "+userName+" 不存在！");
		
		//加载用户权限
		UserDetails userDetail = new UserInfoDetails(t,findAuhts(resourceInfoService.findByPersonResource(t.getId()))); 
        
		return userDetail;
	}
	
	
	private Collection<GrantedAuthority> findAuhts(List<ResourceInfo> list){
		
		Collection<GrantedAuthority> auths = null;
		
		if(null!=list){
			
			auths = new ArrayList<GrantedAuthority>();
			
			for(ResourceInfo t : list){
				
				if(ResourceTypeEnum.URL_RESOURCE.equals(ResourceTypeEnum.toEnum(t.getType()))){
					
					GrantedAuthority auth = new SimpleGrantedAuthority(t.getId().toString());
					
					auths.add(auth);
					
				}else if(ResourceTypeEnum.COMPONENT_RESOURCE.equals(ResourceTypeEnum.toEnum(t.getType()))){
					
					GrantedAuthority auth = new SimpleGrantedAuthority(t.getCode());
					
					auths.add(auth);
				}
				
			}
		}
		
		return auths;
	}

}
